package com.hange.excel.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hange.excel.model.pojo.Celldata;
import com.hange.excel.model.pojo.WorksheetConfig;
import com.hange.excel.service.CelldataService;
import com.hange.excel.service.IMessageProcess;
import com.hange.excel.service.WorksheetConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @descriptions: TODO
 * @author: 涵哥
 * @date: 2024/3/17 18:38
 */
@Service
@Slf4j
public class MessageProcess implements IMessageProcess {

    @Autowired
    private WorksheetConfigService worksheetConfigService;

    @Autowired
    private CelldataService celldataService;
    /**
     * 对updateurl发来的信息进行处理
     *
     * @param gridKey       工作簿标识
     * @param message       消息
     * @return
     */
    @Override
    public void process(String gridKey, JSONObject message) {
        //获取操作名
        String action = message.getStr("t");
        //获取sheet的index值
        String index = message.getStr("i");

        //如果是复制sheet，index的值需要另取
        if ("shc".equals(action)) {
            index = message.getJSONObject("v").getStr("copyindex");
        }

        //如果是删除sheet，index的值需要另取
        if ("shd".equals(action)) {
            index = message.getJSONObject("v").getStr("deleIndex");
        }

        //如果是恢复sheet，index的值需要另取
        if ("shre".equals(action)) {
            index = message.getJSONObject("v").getStr("reIndex");
        }
        // 根据gridKey和sheet索引来找到工作页的信息
        WorksheetConfig wsc = worksheetConfigService.getSheetListByWorkIdAndSheetId(gridKey, index);
        switch (action) {
            //单个单元格刷新
            case "v":
                singleCellRefresh(message);
                break;
            //范围单元格刷新
            case "rv":
                rangeCellRefresh(wsc,message);
                break;
            default:
                log.info("等待开发");
        }

    }

    /**
     * 范围单元格刷新
     * @param message       字符内容
     */
    private void rangeCellRefresh(WorksheetConfig wsc,JSONObject message) {
        JSONArray rowArray = message.getJSONObject("range").getJSONArray("row");//行
        JSONArray columnArray = message.getJSONObject("range").getJSONArray("column");//列
        JSONArray vArray = message.getJSONArray("v");//内容
        // 拿到sheet所有单元格数据
        List<Celldata> celldataList = wsc.getCelldataList();
        int countRowIndex = 0;
        //遍历行列，对符合行列的内容进行更新
        for (int ri = (int) rowArray.get(0); ri <= (int) rowArray.get(1); ri++) {
            int countColumnIndex = 0;
            for (int ci = (int) columnArray.get(0); ci <= (int) columnArray.get(1); ci++) {
                List<String> flag = new ArrayList<>();
                Object newCell = JSONUtil.parseArray(vArray.get(countRowIndex)).get(countColumnIndex);
                int rowIndex = ri;
                int columnIndex = ci;
                celldataList.forEach(cell -> {
                    JSONObject jsonObject = JSONUtil.parseObj(cell.getValue());
                    if (cell.getRowNum() == rowIndex && cell.getColNum() == columnIndex) {
                        if ("null".equals(newCell.toString()) || JSONUtil.parseObj(newCell).isEmpty()) {
                            celldataService.remove(new LambdaQueryWrapper<Celldata>().eq(Celldata::getColNum,cell.getColNum()).eq(Celldata::getRowNum,cell.getRowNum()).eq(Celldata::getWorksheetId,message.getStr("i")));
                        } else {
                            Celldata c = new Celldata(cell.getId(), message.getStr("i"), cell.getRowNum(), cell.getColNum(), newCell.toString());
                            celldataService.saveOrUpdate(c);
                        }
                        flag.add("used");
                    }
                });
                if (flag.isEmpty() && !JSONUtil.parseObj(newCell).isEmpty()) {
                    Celldata celldata = new Celldata(null,message.getStr("i"),ri,ci,newCell.toString());
                    celldataService.save(celldata);
                }
                countColumnIndex++;
            }
            countRowIndex++;
        }
    }

    /**
     * 单个单元格刷新
     * message样例：{"t":"v","i":"1","v":{"m":"dfgh","ct":{"fa":"General","t":"g"},"v":"dfgh"},"r":1,"c":2}
     * @param message   报文
     * @return          返回
     */
    private void singleCellRefresh(JSONObject message) {
        // 官方文档：如果存在该单元格则更新，如果没有则添加，如果存在该单元格但是v为null则删除该单元格
        Integer r = message.getInt("r");//行
        Integer c = message.getInt("c");//列
        // sheet索引
        String i = message.getStr("i");
        // 内容
        String v = message.getStr("v");
        String value = JSONUtil.parseObj(v).getStr("m");
        if (StrUtil.isNotBlank(value)){
            // 说明要添加 或者更新
            Celldata celldata = new Celldata(null, i, r, c,message.getStr("v"));
            celldataService.save(celldata);
        }else {
            // 删除
            celldataService.remove(new LambdaQueryWrapper<Celldata>().eq(Celldata::getColNum,c).eq(Celldata::getRowNum,r).eq(Celldata::getWorksheetId,i));
        }
    }
}
